<template>
    <div class="app-container">
        <!-- 项目信息表单 -->
        <template v-if="form.pid || pid">
            <el-divider content-position="left"><strong>项目信息</strong></el-divider>
            <!-- <el-row :gutter="24"> -->
            <el-form :modal="projectForm" disabled ref="projectForm" size="small" :inline="true" label-width="80px">
                <!-- <el-col :span="6"> -->
                <el-form-item label="客户" prop="custom">
                    <el-input v-model="projectForm.custom" placeholder="请输入客户" />
                </el-form-item>
                <!-- </el-col>
                    <el-col :span="6"> -->
                <el-form-item label="机型" prop="model">
                    <el-input v-model="projectForm.model" placeholder="请输入机型" />
                </el-form-item>
                <!-- </el-col>
                    <el-col :span="6"> -->
                <el-form-item label="项目编码" prop="projectNo">
                    <el-input v-model="projectForm.projectNo" placeholder="请输入项目编码" />
                </el-form-item>
                <!-- </el-col>
                    <el-col :span="6"> -->
                <el-form-item label="专案类别" prop="level">
                    <el-input v-model="projectForm.level" placeholder="请输入专案类别" />
                </el-form-item>
                <!-- </el-col>
                    <el-col :span="6"> -->
                <el-form-item label="芯片组" prop="chipGroup">
                    <el-input v-model="projectForm.chipGroup" placeholder="请输入芯片组" />
                </el-form-item>
                <!-- </el-col>
                    <el-col :span="6"> -->
                <el-form-item label="AD板" prop="adBoard">
                    <el-input v-model="projectForm.adBoard" placeholder="请输入AD板" />
                </el-form-item>
                <!-- </el-col>
                    <el-col :span="6"> -->
                <el-form-item label="LCM/OC" prop="lcmOc">
                    <el-input v-model="projectForm.lcmOc" placeholder="请输入LCM/OC" />
                </el-form-item>
                <!-- </el-col>
                    <el-col :span="6"> -->
                <el-form-item label="电源/适配器" class="labelword" prop="powerSupply">
                    <el-input v-model="projectForm.powerSupply" placeholder="请输入电源/适配器" />
                </el-form-item>
                <!-- </el-col>
                    <el-col :span="6"> -->
                <el-form-item label="恒流板" prop="currentBoard">
                    <el-input v-model="projectForm.currentBoard" placeholder="请输入恒流板" />
                </el-form-item>
                <!-- </el-col>
                    <el-col :span="6"> -->
                <el-form-item label="Arm板" prop="armBoard">
                    <el-input v-model="projectForm.armBoard" placeholder="请输入Arm板" />
                </el-form-item>
                <!-- </el-col>
                    <el-col :span="12"> -->
                <el-form-item label="差异说明" prop="remark">
                    <el-input type="textarea" v-model="projectForm.remark" placeholder="请输入项目差异说明" />
                </el-form-item>
                <!-- </el-col> -->
            </el-form>
            <!-- </el-row> -->
        </template>


        <el-divider content-position="left"><strong>bug信息</strong></el-divider>
        <el-row :gutter="50">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <template v-show="!pid">
                    <el-col :span="6">
                        <el-form-item label="项目编码" prop="pid">
                            <el-select filterable @change="selectChange($event)" v-model="form.pid"
                                placeholder="请选择对应的项目">
                                <el-option v-for="item in projectLists" :key="item.id" :label="item.projectNo"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </template>
                <!-- <el-col :span="150">
                    <el-form-item label="bugCode" prop="bugCode">
                        <el-input v-model="form.bugCode" placeholder="请输入bugCode" />
                    </el-form-item>
                </el-col> -->

                <!-- <el-col :span="150">
                    <el-form-item label="bug标识" prop="identify">
                        <el-input v-model="form.identify" placeholder="请输入bug识别标识" />
                    </el-form-item>
                </el-col> -->
                <el-col :span="6">
                    <el-form-item label="产品阶段" prop="productStage">
                        <el-select filterable clearable v-model="form.productStage" placeholder="请选择产品阶段">
                            <el-option v-for="dict in dict.type.product_stage" :key="dict.value" :label="dict.label"
                                :value="dict.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="问题类别" prop="problemType">
                        <el-select filterable clearable v-model="form.problemType" placeholder="请选择问题类别">
                            <el-option v-for="dict in dict.type.problem_type" :key="dict.value" :label="dict.label"
                                :value="dict.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="严重程度" prop="level">
                        <el-select filterable clearable v-model="form.level" placeholder="请选择严重程度">
                            <el-option v-for="dict in dict.type.problem_level" :key="dict.value" :label="dict.label"
                                :value="dict.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="6">
                    <el-form-item label="设备型号" prop="modelCode">
                        <el-select filterable clearable v-model="form.modelCode" placeholder="请选择设备型号">
                            <el-option v-for="item in stationCodeList" :key="item.id"
                                :label="`${item.code} ${item.shortName}`" :value="item.code"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="6">
                    <el-form-item label="不良率" prop="badPersentage">
                        <!-- <el-input v-model="form.badPersentage" placeholder="请输入不良率" /> -->
                        <el-autocomplete v-model="form.badPersentage" :fetch-suggestions="querySearchAsyncBP"
                            placeholder="请输入不良率" @select="handleSelectBP"></el-autocomplete>
                    </el-form-item>
                </el-col>

                <!-- <el-col :span="150">
                    <el-form-item label="标题" prop="bugTitle">
                        <el-input v-model="form.bugTitle" placeholder="请输入标题" />
                    </el-form-item>
                </el-col> -->
                <el-col :span="6">
                    <el-form-item label="验证版本" prop="bugVersion">
                        <!-- <el-input v-model="form.bugVersion" placeholder="请输入验证版本" /> -->
                        <el-autocomplete v-model="form.bugVersion" :fetch-suggestions="querySearchAsyncBV"
                            placeholder="请输入验证版本" @select="handleSelectBV"></el-autocomplete>
                    </el-form-item>

                </el-col>

                <!-- <el-col :span="6">
                    <el-form-item label="异常归类" prop="exceptionType">
                        <el-select filterable clearable v-model="form.exceptionType" placeholder="请选择异常归类">
                            <el-option v-for="dict in dict.type.exception_type" :key="dict.value" :label="dict.label"
                                :value="dict.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col> -->

                <el-col :span="6">
                    <el-form-item label="异常代码" prop="exceptionCode">
                        <el-select filterable clearable v-model="form.exceptionCode" placeholder="请选择异常代码">
                            <el-option v-for="item in exceptionCodeList" :key="item.id"
                                :label="`${item.code} ${item.type}`" :value="item.code"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="6">
                    <el-form-item label="指派人" prop="rdHandle">
                        <el-select filterable multiple clearable v-model="form.rdHandle" :disabled="edit"
                            placeholder="请选择指派人">
                            <el-option v-for="item in rdHandleList" :key="item.userId" :label="item.nickName"
                                :value="item.userId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="6">
                    <el-form-item label="电源/适配器标识" class="labelword" prop="powerSuppleId">
                        <el-input v-model="form.powerSuppleId" placeholder="项目多个电源/适配器时填写具体标识" />
                    </el-form-item>
                </el-col>

                <el-col :span="6">
                    <el-form-item label="lcm/oc标识" class="labelword" prop="lcmOcId">
                        <el-input v-model="form.lcmOcId" placeholder="项目多个lcm/oc时填写具体标识" />
                    </el-form-item>
                </el-col>

                <!-- <el-col :span="6">
                    <el-form-item label="上传附件" prop="fileId">
                        <el-button type="success">选择文件</el-button>
                    </el-form-item>
                </el-col> -->

                <el-col>
                    <el-form-item label="标题" prop="bugTitle">
                        <el-input v-model="form.bugTitle" placeholder="请输入标题" />
                    </el-form-item>
                </el-col>
                <el-col>
                    <el-form-item label="描述" prop="descriptions">
                        <!-- <el-input  type="textarea" v-model="form.descritions" placeholder="请输入bug描述" /> -->
                        <editor ref="editor" :min-height="300" :type="`url`" v-model.trim="form.descriptions" />
                    </el-form-item>
                </el-col>
                <!-- <el-form-item >
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </el-form-item> -->
            </el-form>
            <el-col>
                <div style="width: 100%;text-align: center;" v-show="buttonView">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </el-col>

        </el-row>
    </div>
</template>

<script>
import { listBugs, getBugs, addBugs, updateBugs } from "@/api/business/bugs"
import { getProjectDetail, projectList } from "@/api/business/project";
import { getUserByPostCode, getUsersByRolekey } from "@/api/system/user";
import { listCodeData } from "@/api/business/code";
import { listAllStation } from "@/api/business/station";
import sesionCatch from "@/utils/LocalCatch";

export default {
    name: 'BugsForm',
    dicts: ['problem_type', 'product_stage', 'problem_level', 'exception_type'],
    props: {
        open: {
            type: Boolean,
            default: false,
        },
        title: {
            type: String,
            default: '',
        },
        isUpdate: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        // var validProofingQty = ((rule, value, callback) => {
        //     if (!value) {
        //         return callback(new Error("打样数量不能为空！"))
        //     }
        //     if (!Number.isInteger(value)) {
        //         callback(new Error('请输入数字值'));
        //     }
        //     callback()
        // });
        // var validSoQty = ((rule, value, callback) => {
        //     if (!value) {
        //         return callback(new Error("订单数量不能为空！"))
        //     }
        //     if (!Number.isInteger(value)) {
        //         callback(new Error('请输入数字值'));
        //     }
        //     callback()
        // });
        return {
            bvHistory: [],
            upPid: undefined,
            edit: false,//是否可以选择指派人
            exceptionCodeList: [],//异常code列表
            stationCodeList: [],//站台code列表
            buttonView: true,
            projectLists: [],//项目数据列表
            pid: null,//项目id
            rdHandleList: [],//指派人数据列表 
            pjmList: [],
            hardList: [],
            opticsList: [],
            softList: [],
            stuList: [],
            NPIList: [],
            form: { descriptions: `<p><strong>步骤：</strong></p><p><strong>结果：</strong></p><p><strong>期望：</strong></p>` },//表单数据对象
            projectForm: { custom: null },//项目表单数据对象
            rules: {
                pid: [
                    { required: true, message: "项目编码不能为空", trigger: "blur" }
                ],
                // bugTitle: [
                //     { required: true, message: "标题不能为空！", trigger: "blur" }
                // ],
                bugVersion: [
                    { required: true, message: "验证版本不能为空！", trigger: "blur" }
                ],
                // exceptionType: [
                //     { required: true, message: "异常归类不能为空！", trigger: "blur" }
                // ],
                productStage: [
                    { required: true, message: "产品阶段不能为空", trigger: "blur" }
                ],
                badPersentage: [
                    { required: true, message: "不良率不能为空", trigger: "blur" }
                ],
                level: [
                    { required: true, message: "严重程度不能为空", trigger: "blur" }
                ],
                rdHandle: [
                    { required: true, message: "指派人不能为空", trigger: "blur" }
                ],
                adBoard: [
                    { required: true, message: "AD板不能为空", trigger: "blur" }
                ],
                lcmOc: [
                    { required: true, message: "lcmOc不能为空", trigger: "blur" }
                ],
                powerSupply: [
                    { required: true, message: "电源/适配器不能为空", trigger: "blur" }
                ],
                currentBoard: [
                    { required: true, message: "恒流板不能为空", trigger: "blur" }
                ],
                armBoard: [
                    { required: true, message: "Arm板不能为空", trigger: "blur" }
                ],
                pjm: [
                    { required: true, message: "项目经理不能为空", trigger: "blur" }
                ],
                problemType: [
                    { required: true, message: "问题类别不能为空", trigger: "blur" }
                ],
                descriptions: [
                    { required: true, message: "问题描述不能为空", trigger: "blur" }
                ],
            },
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() < Date.now();
                },
            },
        }
    },
    created() {
        this.reset()
        //创建时传的项目id
        this.pid = this.$route.query.pid//项目id
        //修改时传的bug id
        this.form.id = this.$route.query.id//bug id
        //修改对应项目下的bug时传的标识
        this.upPid = this.$route.query.upPid//bug标识
        if (this.pid) {
            this.form.pid = this.pid
            //获取项目详情
            this.getProjectFormDate(this.pid);
        }
        if (this.form.id) {
            this.getBugsFormDate(this.form.id)
            this.edit = true//修改禁止选择指派人
        }
        this.getProjectList()
        this.getRdHandleList()
        this.getExceptionCode()
        this.getStationCode()
        // this.getPjmUserList()
        // this.getHardUserList()
        // this.getOpticsUserList()
        // this.getStuUserList()
        // this.getNPIUserList()
        // this.getSoftUserList()
    },
    mounted() {
        //获取富文本编译器对象
        let quill = this.$refs.editor.Quill
        quill.pasteHTML(`<strong>步骤：</strong><br><strong>结果：</strong><br><strong>期望：</strong>`)
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 调整光标到最后
        quill.setSelection(length + 3);
    },
    methods: {
        //获取sesion历史填写的版本数据
        querySearchAsyncBV(queryString, cb) {
            // sesionCatch.remove("BVHistory")
            const arr = sesionCatch.get("BVHistory")
            if (arr) {
                let arr2 = arr.split(",")
                let arr3 = []
                // console.log(arr2)
                for (let res of arr2) {
                    let param = JSON.parse(res)
                    arr3.push(param)
                }
                var restaurants = arr3;
                var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
                cb(results)
            } else {
                cb([])
            }

        },
        //获取sesion历史填写的不良率数据
        querySearchAsyncBP(queryString, cb) {
            // sesionCatch.remove("BPHistory")
            const arr = sesionCatch.get("BPHistory")
            if (arr) {
                let arr2 = arr.split(",")
                let arr3 = []
                // console.log(arr2)
                for (let res of arr2) {
                    let param = JSON.parse(res)
                    arr3.push(param)
                }
                var restaurants = arr3;
                var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
                cb(results);
            } else {
                cb([])
            }

        },
        handleSelectBP(item) {
            this.form.badPersentage = item.value
            this.$refs.form.validateField('badPersentage', (valid) => {});
        },
        handleSelectBV(item) {
            this.form.bugVersion = item.value
            this.$refs.form.validateField('bugVersion', (valid) => {});
        },
        createStateFilter(queryString) {
            return (state) => {
                return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
        },
        // 获取站台代码code
        getStationCode() {
            listAllStation().then(result => {
                this.stationCodeList = result.data
            })
        },
        getBugsFormDate(id) {
            getBugs(id).then(result => {
                this.form = result.data
                //获取对应项目的表单数据
                this.getProjectFormDate(result.data.pid)
            })
        },
        selectChange(event) {
            this.getProjectFormDate(event);
        },
        //获取项目表单数据
        getProjectFormDate(id) {
            getProjectDetail(id).then(result => {
                // console.log(result,"project");
                this.projectForm = result.data;
            })
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                pid: null,
                bugCode: null,
                identify: null,
                level: null,
                modelCode: null,
                badPersentage: null,
                bugTitle: null,
                problemType: null,
                bugVersion: null,
                exceptionCode: null,
                respon: null,
                rdHandle: [],
                productStage: null,
                // remark: null,
                descriptions: undefined,
                powerSuppleId: undefined,
                lcmOcId: undefined,
            };
            this.resetForm("form");
        },
        // 取消按钮
        cancel() {
            this.reset();
            //关闭当前页面
            this.$store.dispatch("tagsView/delView", this.$route);
            // console.log(this.upPid,"flage");
            if (this.pid || this.upPid) {
                this.$nextTick(() => {
                    this.$router.push({
                        name: 'projectBugs',
                        query: {
                            id: this.pid ? this.pid : this.upPid,
                        }
                    })
                })
            } else {
                this.$nextTick(() => {
                    this.$router.push({
                        name: 'Bugs',
                        query: {
                            id: undefined,
                        }
                    })
                })
            }

        },
        /**新增bug或者修改bug提交按钮 */
        submitForm() {
            // console.log(this.form.descriptions)
            if (this.form.descriptions == '<p><br></p>') {
                this.$message.error("请输入邮件的内容！")
            } else {
                this.buttonView = false
                this.$refs["form"].validate(valid => {
                    let flag = false
                    if (valid) {
                        // console.log(this.form);
                        flag = true
                        this.$modal.loading("正在处理请稍等....")
                        if (this.form.id) {
                            updateBugs(this.form).then(response => {
                                this.$modal.msgSuccess("修改成功")
                                this.$modal.closeLoading()
                                this.cancel()
                                this.buttonView = true
                            }).catch(
                                () => {
                                    this.buttonView = true
                                }
                            );
                            this.$modal.closeLoading()
                        } else {
                            addBugs(this.form).then(response => {
                                this.$modal.msgSuccess("创建成功")
                                this.$modal.closeLoading()
                                this.cancel()
                                this.buttonView = true
                            }).catch(
                                () => {
                                    this.buttonView = true
                                }
                            );
                            this.$modal.closeLoading()
                        }
                        //设置本地缓存
                        sesionCatch.set("BVHistory", { "value": this.form.bugVersion })
                        sesionCatch.set("BPHistory", { "value": this.form.badPersentage })
                    }
                    if (!flag) {
                        this.buttonView = true
                    }
                });
            }
        },
        /**
         * 获取指派人列表(rd,npi)
         */
        getRdHandleList() {
            let rdList = []
            let npiList = []
            let nwbgysList = []
            getUsersByRolekey(this.$store.state.globalParam.RDROLE).then(result => {
                rdList = result.data
                getUsersByRolekey(this.$store.state.globalParam.NPI).then(result => {
                    npiList = result.data
                    this.rdHandleList = rdList.concat(npiList)
                    
                    //外部供应商
                    getUsersByRolekey(this.$store.state.globalParam.WBGYS).then(result => {
                        nwbgysList = result.data
                        this.rdHandleList = this.rdHandleList.concat(nwbgysList)
                    })


                })

            })

        },
        /**
         * 获取项目经理列表
         */
        getPjmUserList() {
            getUserByPostCode(this.$store.state.globalParam.PJM).then(result => {
                this.pjmList = result.data
            })
        },
        /**
         * 获取硬件工程师列表
         */
        getHardUserList() {
            getUserByPostCode(this.$store.state.globalParam.HARD).then(result => {
                this.hardList = result.data
            })
        },
        /**
        * 获取软件工程师列表
        */
        getSoftUserList() {
            getUserByPostCode(this.$store.state.globalParam.SOFT).then(result => {
                this.softList = result.data
            })
        },
        /**
        * 获取光学工程师列表
        */
        getOpticsUserList() {
            getUserByPostCode(this.$store.state.globalParam.OPTICS).then(result => {
                this.opticsList = result.data
            })
        },
        /**
        * 获取结构工程师列表
        */
        getStuUserList() {
            getUserByPostCode(this.$store.state.globalParam.STU).then(result => {
                this.stuList = result.data
            })
        },
        /**
        * 获取工厂NPI列表
        */
        getNPIUserList() {
            getUserByPostCode(this.$store.state.globalParam.NPI).then(result => {
                this.NPIList = result.data
            })
        },
        //获取项目详情
        getProjectBYId(id) {
            getProjectDetail(id).then(result => {
                this.form = result.data
            })
        },
        /**
        * 获取系统所有的项目数据
        */
        getProjectList() {
            projectList().then(result => {
                this.projectLists = result.data;
            })
        },
        /**
         * 获取系统异常代码列表
         */
        getExceptionCode() {
            listCodeData().then(result => {
                this.exceptionCodeList = result.data;
            })
        },
    }
}
</script>

<style lang="scss" scoped>
// .el-col {
//     height: 60px;
// }
.labelword ::v-deep .el-form-item__label {
    white-space: pre-line !important;
    line-height: 15px !important;
}

.app-container {
    overflow-x: hidden;
    overflow-y: auto;
}
</style>